package com.softwinner.bt.Fragment;

import java.util.ArrayList;

import com.softwinner.bt.BtApplication;
import com.softwinner.bt.CallDialog;
import com.softwinner.bt.R;
import com.softwinner.bt.adapter.ContactAdapter;
import com.softwinner.bt.bean.BtContact;
import com.softwinner.bt.policy.BTManager;
import com.softwinner.bt.service.BtService;
import com.softwinner.bt.util.Command;
import com.softwinner.bt.util.DatabaseHelper;
import com.softwinner.bt.util.Utils;

import android.app.Fragment;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import android.content.pm.IPackageDataObserver;
public class ContactFragment extends BaseFragment implements OnClickListener {
    private ArrayList<BtContact> contacts;
    private ContactAdapter mAdapter;
    private MainHandler mHandler = new MainHandler();
	private ListView mList;
	private ProgressDialog mProgressDialog;
	
	private final static int UPDATE_NUMBER = 0;
	private final static int WHAT_DIALOG_OVERTIME = 1;
	
	private Button mUpload;
	private Button mDialer;
	private Button mBack;
	private Button mDel;
	
	public static boolean background=false;
	
	private BroadcastReceiver receiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context arg0, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			mHandler.removeMessages(WHAT_DIALOG_OVERTIME);
			if(Utils.ACTION_UPDATE_CONTACTS.equals(action)){				
				updateNumber();
				//Log.i(TAG, "action===ACTION_UPDATE_CONTACTS");
				//showProgressDialog();
				//mProgressDialog.setMessage(getString(R.string.uploading));				
			}else if(Utils.ACTION_FINISH_CONTACTS.equals(action)){
                updateNumber();
                //disProgressDialog();
                Toast.makeText(ContactFragment.this.getActivity(), "共同步了 "+contacts.size()+" 个联系人！", 3000).show();
			}else if(Utils.ACTION_BTSTATE_CHANGED.equals(action)){
				updateNumber();
			}
		}
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.bt_contact_fragment, container, false);
		initView(view);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mDatabaseHelper = DatabaseHelper.getDatabaseHelper(mActivity);
		contacts =  new ArrayList<BtContact>();
		contacts = mDatabaseHelper.queryAllContacts();
		updateNumber();
		mAdapter = new ContactAdapter(mActivity, contacts);
		mList.setOnItemClickListener(mOnItemClickListener);
        mList.setAdapter(mAdapter);
        
        IntentFilter filter = new IntentFilter();
        filter.addAction(Utils.ACTION_UPDATE_CONTACTS);
        filter.addAction(Utils.ACTION_FINISH_CONTACTS);
        filter.addAction(Utils.ACTION_BTSTATE_CHANGED);
        getActivity().registerReceiver(receiver, filter);
	}
	
	private void initView(View view){
		mUpload = (Button)view.findViewById(R.id.list_upload);
		mDialer = (Button)view.findViewById(R.id.list_dialer);
		mBack = (Button)view.findViewById(R.id.list_back);
		mDel = (Button)view.findViewById(R.id.list_del);
		mList = (ListView)view.findViewById(R.id.bt_list);
		mUpload.setOnClickListener(this);
		mDialer.setOnClickListener(this);
		mBack.setOnClickListener(this);
		mDel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
        case R.id.list_upload:
        	if(mActivity.getState() != BTManager.STATE_CONNECTED){
        		Toast.makeText(mActivity, R.string.msg_unconnectedorcalling, 1000).show();
        		return;
        	}
            mBTManager.sendCommand(Command.SEND_UPLOAD_CONTACTS);
            background = false;
            showProgressDialog();
            mHandler.sendEmptyMessageDelayed(WHAT_DIALOG_OVERTIME, 10*1000);
            break;
        case R.id.list_dialer:
            call();
            break;
        case R.id.list_back:
            if (mCurrentPosition>=0 && contacts.size() > 0 && mCurrentPosition < contacts.size()) {
                mDatabaseHelper.deleNumber(contacts.get(mCurrentPosition)
                        .getNumber());
                updateNumber();
                mCurrentPosition = -1;
                mAdapter.setSelected(mCurrentPosition);
            }
            break;
        case R.id.list_del:
            if (contacts.size() > 0) {
                mDatabaseHelper.delAllNumber();
                updateNumber();
                mCurrentPosition = 0;
				 //跳转到联系人存储详细页面执行清空联系人操作
	                Intent intent=new Intent();
	                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
	                intent.setData(Uri.parse("package:com.android.providers.contacts"));
	                getActivity().startActivity(intent);
            }
            break;
        }
	}
	
	public void showProgressDialog(){
		if(mProgressDialog==null){			
			mProgressDialog = new ProgressDialog(mActivity);     
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);             
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.setCancelable(false);
			mProgressDialog.setMessage(getString(R.string.uploadmss));
			mProgressDialog.setButton(getString(R.string.uploadbackground), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					background = true;
					disProgressDialog();
				}
			});			
		}
		if(!mProgressDialog.isShowing()&&!background)
			mProgressDialog.show();
	}
	
	public void disProgressDialog(){
		if(mProgressDialog!=null && mProgressDialog.isShowing())
			mProgressDialog.dismiss();
	}
	
	private void updateNumber() {
        new Thread() {
            public void run() {
                contacts = mDatabaseHelper.queryAllContacts();
                mHandler.sendEmptyMessage(UPDATE_NUMBER);
            }
        }.start();
    }
	
	private int mCurrentPosition = 0;
    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View convertView,
                int position, long arg3) {
            mCurrentPosition = position;
            mAdapter.setSelected(position);
            mAdapter.notifyDataSetChanged();
        }
    };

    private void call() {
        if (!(contacts.size() > 0)) {
            return;
        }
        if(mActivity.getState() != BTManager.STATE_CONNECTED){
    		Toast.makeText(mActivity, R.string.msg_unconnectedorcalling, 1000).show();
    		return;
    	}
        BtContact contact = contacts.get(mCurrentPosition);
        String number = contact.getNumber();
        mBTManager.sendCommand(Command.SEND_MAKECALL + number);
    }

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(receiver);
		super.onDestroy();
	}

	private class MainHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
            case UPDATE_NUMBER:
                mAdapter.setDataChange(contacts);
                break;
            case WHAT_DIALOG_OVERTIME:
            	disProgressDialog();
            	break;
            default:
                break;
            }
        }
    }
	
}
